/**
 * 版权所有(C) COVISINT 2015-2025
 * Copyright 2015-2025 COVISINT
 * 创建日期：Jun 29, 20172:29:30 PM
 * 创建人：yyang
 */
package com.wechat.framework.utils;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.covisint.platform.GsonUtils.GsonUtils;
import com.covisint.platform.httpclient.utils.HttpClientUtils;
import com.wechat.framework.messages.oauth.OAuthUser;
import com.wechat.framework.messages.token.AccessToken;
import com.google.gson.reflect.TypeToken;

public class WechatSupportUtils {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	
	@Resource
	public static HttpClientUtils httpClientUtils;
	
	public static AccessToken getAccessToken(String corpID, String secret) {
		
		AccessToken accessToken = null;  
		  
	    String requestUrl = WechatURLUtils.ACCESS_TOKEN_URL.replace("CorpID", corpID).replace("SECRET", secret);
	    
	    try {
			String jsonResult = httpClientUtils.doGet(requestUrl);
			System.out.println(jsonResult);
			
			//返回结果不为空
			if(null != jsonResult){
				accessToken = GsonUtils.convert(jsonResult, new TypeToken<AccessToken>(){});
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
 
	    return accessToken;
	}

	public static String findOAuth2GetUserIdByCode(String accessToken, String code, String agentId) {
		
		OAuthUser oauthUser = null;

		String requestUrl = WechatURLUtils.GET_OAUTH2_URL.replace("ACCESS_TOKEN", accessToken).replace("CODE", code).replace("AGENTID", agentId);
		
		try {
			String jsonResult = httpClientUtils.doGet(requestUrl);
			System.out.println(jsonResult);
			//返回结果不为空
			if(null != jsonResult){
				oauthUser = GsonUtils.convert(jsonResult, new TypeToken<OAuthUser>(){});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if (null != oauthUser && oauthUser.getUserId() != null) {
			return oauthUser.getUserId();
		}

		return null;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
